<template>
    <div class="page-container">
        <!-- 头部 -->
        <div class="page-filter">
            <el-input v-model="couponFilter.title" placeholder="请选择优惠券名称" />
            <el-select v-model="couponFilter.type" class="m-2" placeholder="请选择优惠券类型">
                <el-option v-for="item in couponTypeDic" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
            <el-select v-model="couponFilter.status" class="m-2" placeholder="请选择优惠券状态">
                <el-option v-for="item in couponStatusDic" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
            <el-button :icon="Search" type="primary" @click="getCouponList">查找</el-button>
            <el-button :icon="Plus" type="primary" @click="handleAddCoupon" v-permission="'promotion:coupon:create'">添加</el-button>
            <el-button :icon="Download" type="primary" @click="saveFile()">当前页导出</el-button>
        </div>
        <!-- 数据列表 -->
        <div class="page-table">
            <el-table :data="couponList" border style="width: 100%" stripe id="exportTab">
                <el-table-column prop="id" label="优惠券ID" />
                <el-table-column prop="title" label="优惠券名称" />
                <el-table-column prop="type" label="优惠券类型">
                    <template #default="scope">
                        {{ scope.row.type === 2 ? '立减' : '满减' }}
                    </template>
                </el-table-column>
                <el-table-column prop="description" label="介绍" />
                <el-table-column prop="total" label="优惠券数量" />
                <el-table-column prop="surplus" label="剩余数量" />
                <el-table-column prop="limit" label="每人限领" />
                <el-table-column label="满减金额">
                    <template #default="scope">
                        减免{{ scope.row.discount }}元
                    </template>
                </el-table-column>
                <el-table-column label="最低消费">
                    <template #default="scope">
                        最低消费{{ scope.row.min }}元
                    </template>
                </el-table-column>
                <el-table-column label="状态">
                    <template #default="scope">
                        <template v-if="scope.row.gmtEnd < (new Date().getTime())">
                            <el-tag type="danger">已过期</el-tag>
                        </template>
                        <template v-else>
                            <el-tag type="danger" v-if="scope.row.status === 0">下架</el-tag>
                            <el-tag v-else-if="scope.row.status === 1">正常</el-tag>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column label="使用类目名称">
                    <template #default="scope">
                        <el-tag v-if="scope.row.categoryTitle">{{ scope.row.categoryTitle }}</el-tag>
                        <el-tag v-else>全部类目</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="categoryId" label="使用类目ID" />
                <el-table-column label="领券相对天数">
                    <template #default="scope">
                        {{ scope.row.days ? scope.row.days : '无' }}
                    </template>
                </el-table-column>
                <el-table-column label="领券开始时间">
                    <template #default="scope">
                        {{ scope.row.gmtStart ? moment(scope.row.gmtStart).format('YYYY-MM-DD hh:mm:ss') : '无' }}
                    </template>
                </el-table-column>
                <el-table-column label="领券结束时间">
                    <template #default="scope">
                        {{ scope.row.gmtEnd ? moment(scope.row.gmtEnd).format('YYYY-MM-DD hh:mm:ss') : '无' }}
                    </template>
                </el-table-column>
                <el-table-column prop="date" label="操作">
                    <template #default="scope">
                        <el-button type="primary" v-if="scope.row.status === -1">已过期</el-button>
                        <el-button type="danger" v-else-if="scope.row.status === 1"
                            @click="handleActivate(scope.row)">冻结</el-button>
                        <el-button type="primary" v-else @click=handleActivate(scope.row)>激活</el-button>
                        <el-button type="info" @click="handleView(scope.row)">查看</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 分页 -->
        <div style="overflow: hidden;">
            <Pagination v-bind="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
        <!-- 添加对话框 -->
        <el-dialog v-model="dialogFormVisible" :title="dialogTitle" @close="handleCloseDialog">
            <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" :disabled="formDisabled">
                <el-form-item label="优惠券名称" prop="title">
                    <el-input v-model="ruleForm.title" clearable />
                </el-form-item>
                <el-form-item label="优惠券类型" prop="type">
                    <el-select v-model="ruleForm.type" class="m-2" placeholder="请选择优惠券状态">
                        <el-option v-for="item in couponTypeDic.slice(0, 2)" :key="item.value" :label="item.name"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="介绍">
                    <el-input v-model="ruleForm.description" clearable />
                </el-form-item>
                <el-form-item label="优惠券数量" prop="total">
                    <el-input v-model="ruleForm.total" clearable>
                        <template #append>张</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="每人限领" prop="limit">
                    <el-input v-model="ruleForm.limit" clearable>
                        <template #append>张</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="最低消费" prop="min">
                    <el-input v-model="ruleForm.min" clearable>
                        <template #append>元</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="优惠券金额" prop="discount">
                    <el-input v-model="ruleForm.discount" clearable>
                        <template #append>元</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="优惠券状态" prop="status">
                    <el-select v-model="ruleForm.status" class="m-2" placeholder="请选择优惠券状态">
                        <template v-if="!formDisabled">
                            <el-option v-for="item in couponStatusDic.slice(0, 2)" :key="item.value" :label="item.name"
                                :value="item.value" />
                        </template>
                        <template v-else>
                            <el-option v-for="item in couponStatusDic.slice(0, 3)" :key="item.value" :label="item.name"
                                :value="item.value" />
                        </template>
                    </el-select>
                </el-form-item>
                <el-form-item label="有效期">
                    <el-radio-group v-model="ruleForm.timeType" style="margin-bottom: 10px;">
                        <el-radio-button :label="0">领取相对天数</el-radio-button>
                        <el-radio-button :label="1">指定绝对时间</el-radio-button>
                    </el-radio-group>
                    <el-input v-model="ruleForm.days" v-if="ruleForm.timeType === 0" clearable>
                        <template #append>天</template>
                    </el-input>
                    <div class="block" v-else>
                        <el-date-picker v-model="ruleForm.gmtStart" type="datetime" placeholder="请选择起始时间" /> 至
                        <el-date-picker v-model="ruleForm.gmtEnd" type="datetime" placeholder="请选择结束时间" />
                    </div>
                </el-form-item>
                <el-form-item label="商品限制范围">
                    <el-radio-group v-model="ruleForm.goodsType" style="margin-bottom: 10px;">
                        <el-radio-button :label="0">全场通用</el-radio-button>
                        <el-radio-button :label="1">指定分类</el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="优惠类目" v-if="ruleForm.goodsType === 1">
                    <el-cascader v-model="ruleForm.categoryList" :options="options" :props="props" clearable />
                </el-form-item>
                <el-form-item style="position:absolute;bottom:10px;right:20px;">
                    <el-button type="primary" @click="submitForm(ruleFormRef)">
                        确定
                    </el-button>
                    <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { post } from '@/utils/http';
import { Plus, Search, Download } from '@element-plus/icons-vue';
import { reactive, ref, onMounted } from 'vue';
import { ClassCoupon, ClassPagination, EnumDialogTitle } from '#/index';
import { ElMessage } from 'element-plus';
import moment from 'moment';
import type { FormInstance, FormRules } from 'element-plus'
import saveFile from "@/utils/saveFile"

//头部过滤对象
const couponFilter = reactive({
    title: undefined,
    type: undefined,
    status: undefined
})
//头部下拉框内容
const couponTypeDic = [{ name: '满减券', value: 1 }, { name: '立减券', value: 2 }, { name: '全部', value: '' }]
const couponStatusDic = [{ name: '下架', value: 0 }, { name: '正常', value: 1 }, { name: "已过期", value: -1 }, { name: '全部', value: '' }]
//优惠券数据
const couponList = ref([{} as ClassCoupon])

//分页对象
const pagination = reactive(new ClassPagination())
//是否显示对话框
const dialogFormVisible = ref(false)
//分类树数据
const options = ref()
const formDisabled = ref(false)
//表单节点
const ruleFormRef = ref<FormInstance>()
//表单类型
class ClassRuleForm extends ClassCoupon {
    /**
     * 有效期类型 0：相对天数，1：指定时间
     */
    timeType = 0
    /**
     * 商品限制范围 0：全场通用，1：指定范围
     */
    goodsType = 0
    /**
     * 接受分类树的数组
     */
    categoryList?: Array<number>
}
//表单对象
const ruleForm = reactive(new ClassRuleForm())

//检验优惠金额不能大于最低消费
const validateDiscount = (rule: any, value: any, callback: any) => {
    if (value == 0 || value == "") {
        callback(new Error('不能为空或者0'))
    } else {
        if (!/^(0|[1-9]\d*)$/.test(value)) {
            callback(new Error('请正确输入数字格式'))
        }
        if (!(value < Number(ruleForm.min))) {
            callback(new Error('优惠金额不能大于最低消费'))
        }
        callback()
    }
}
//检验个人领取数
const validateLimit = (rule: any, value: any, callback: any) => {
    console.log(value)
    if (value == 0 || value == "") {
        callback(new Error('不能为空或者0'))
    } else {
        if (!/^(0|[1-9]\d*)$/.test(value)) {
            callback(new Error('请正确输入数字格式'))
        }
        if (!(value < Number(ruleForm.total))) {
            callback(new Error('个人领取数不能大于数量'))
        }
        callback()
    }
}
//验证规则
const rules = reactive<FormRules>({
    title: [{ required: true, message: '请输入优惠券名称', trigger: 'blur' }],
    type: [{ required: true, message: '请选择类型', trigger: 'change' }],
    total: [{ required: true, pattern: /^(0|[1-9]\d*)$/, message: '请正确输入数字且不能为空', trigger: 'blur' }],
    limit: [{ required: true, validator: validateLimit, trigger: 'blur' }],
    discount: [{ required: true, validator: validateDiscount, trigger: 'blur' }],
    min: [{ required: true, pattern: /^(0|[1-9]\d*)$/, message: '请正确输入数字且不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }],
})
//分类树指定数据
const props = {
    value: "id",
    label: "title",
    children: 'childrenList'
}

//对话框主题
const dialogTitle = ref(EnumDialogTitle.create)
onMounted(() => {
    getCouponList()
    getCategory()
})
/**
 * 添加提交
 * @param formEl form对象节点
 */
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (ruleForm.goodsType === 0) {
                ruleForm.categoryId = undefined
            }
            if (ruleForm.timeType === 0) {
                ruleForm.gmtStart = undefined
                ruleForm.gmtEnd = undefined
            } else {
                ruleForm.days = undefined
                ruleForm.gmtStart = moment(ruleForm.gmtStart).valueOf()
                ruleForm.gmtEnd = moment(ruleForm.gmtEnd).valueOf()
            }
            if (ruleForm.discount && ruleForm.min) {
                ruleForm.discount *= 100
                ruleForm.min *= 100
            }
            if (ruleForm.categoryList) {
                ruleForm.categoryId = ruleForm.categoryList[2]
            }
            const data = { _gp: 'admin.coupon', _mt: 'create', ...ruleForm }
            post(data).then(res => {
                const { data, errmsg, errno } = res
                if (200 === errno) {
                    ElMessage.success('添加成功')
                    dialogFormVisible.value = false
                    getCouponList()
                } else {
                    ElMessage.error(errmsg)
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
/**
 * 取消，关闭对话框
 * @param formEl 
 */
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    Object.assign(ruleForm, new ClassRuleForm())
    dialogFormVisible.value = false
}
/**
 * 获取优惠券数据
 */
function getCouponList() {
    const data = { _gp: 'admin.coupon', _mt: 'list', ...couponFilter, pageNo: pagination.currentPage, limit: pagination.pageSize }
    post(data).then(res => {
        const { data, errmsg, errno } = res
        console.log(data)
        if (200 === errno) {
            const { items, total } = data
            couponList.value = items
            couponList.value.forEach(element => {
                if (element.discount && element.min) {
                    element.discount = element.discount * 0.01
                    element.min = element.min * 0.01
                }

                if (element.gmtEnd && element.gmtEnd < new Date().getTime()) {
                    element.status = -1
                }
            });
            pagination.total = total
        } else {
            ElMessage.error(errmsg)
        }
    })
}
/**
 * 获取分类树
 */
function getCategory() {
    const data = { _gp: 'admin.category', _mt: 'categoryTree' }
    post(data).then(res => {
        const { data, errno } = res
        if (200 === errno) {
            console.log(data)
            options.value = filterData(data)
        } else {
            ElMessage.error('获取分类失败')
        }
    })
}
/**
 * 过滤树数据，不能选择第二层
 * @param arr 数组
 */
function filterData(arr: []) {
    arr.forEach((item: any) => {
        if (item.childrenList) {
            filterData(item.childrenList)
        } else {
            if (item.level < 2) {
                item.disabled = true
            }
        }
    })
    return arr
}
//存储数组
let arrs = ref([] as Array<number>)
/**
 * 找到具体的分类
 * @param arr 遍历的数组
 * @param id 用于判断的id
 */
function filterDataGetId(arr: [], id: number) {
    arr.forEach((item: any) => {
        if (item.childrenList) {
            filterDataGetId(item.childrenList, id)
        } else {
            if (item.id == id) {
                arrs.value = [item.firstLevelId, item.parentId, id]
            }
        }
    })
}
/**
 * 改变一页多少行,防止多次请求
 * @param value 一页多少行
 */
function handleSizeChange(value: number) {
    let tempCurrent = Math.ceil(pagination.total / value)
    if (tempCurrent < pagination.currentPage) {
        pagination.currentPage = tempCurrent
    }
    pagination.pageSize = value
    getCouponList()
}

/**
 * 改变当前页
 * @param value 当前页数
 */
function handleCurrentChange(value: number) {
    pagination.currentPage = value
    getCouponList()
}
/**
 * 
 * @param row 当前行对象
 */
function handleActivate(row: ClassCoupon) {
    const data = { _gp: 'admin.coupon', _mt: 'updateCouponStatus', id: row.id, status: row.status ? 0 : 1 }
    post(data).then(res => {
        const { errno } = res
        if (200 === errno) {
            ElMessage.success('设置成功')
            getCouponList()
        } else {
            ElMessage.error('设置失败')
        }
    })
}
/**
 * 打开对话框
 */
function handleAddCoupon() {
    dialogTitle.value = EnumDialogTitle.create
    dialogFormVisible.value = true
}
/**
 * 关闭对话框
 */
function handleCloseDialog() {
    ruleFormRef.value?.resetFields()
    Object.assign(ruleForm, new ClassRuleForm())
    formDisabled.value = false
}
/**
 * 打开查看对话框
 */
function handleView(row: ClassRuleForm) {
    dialogTitle.value = EnumDialogTitle.view
    Object.assign(ruleForm, row)
    formDisabled.value = true
    dialogFormVisible.value = true
    ruleForm.goodsType = ruleForm.categoryId ? 1 : 0
    ruleForm.timeType = ruleForm.days ? 0 : 1
    if (row.categoryId) {
        filterDataGetId(options.value, row.categoryId)
        ruleForm.categoryList = arrs.value
    }

}
</script>
<style lang="less" scoped>
.page-filter {
    display: flex;

    .el-input {
        width: 200px;
        margin-right: 10px;
    }

    .el-select {
        margin-right: 10px;
    }
}

:deep(.el-input__wrapper) {
    box-sizing: border-box;
}
</style>